package com.virtium.vpm.util;

import java.util.Collection;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.LabelValueBean;

import com.virtium.vpm.controller.UserSession;


/**
 * <p>This class provides Form utility methods that can be used to perform common 
 * operations.</p>
 * <p>It also provides methods to get and clear session values and attributes.</p>
 *
 * @author TuanAnh
 * @version 
 * @since 
 */

public class FormUtil {

	private static Log log = LogFactory.getLog(FormUtil.class);
	
	private FormUtil() {
		
	}

    /**
     * Cleans up session reference.
     *
     * @param request
     * @param sessionName
     */
    public static void removeSessionValue(HttpServletRequest request, String sessionName) {

        HttpSession session = request.getSession(false);
        if (session != null)
            session.removeAttribute(sessionName);
    }

    /**
     * Stores object in session.
     *
     * @param request
     * @param sessionName
     * @param sessionObj
     */
    public static void setSessionValue(HttpServletRequest request, String sessionName,
                                Object sessionObj) {
        HttpSession session = request.getSession(true);
        session.setAttribute(sessionName, sessionObj);
    }

    /**
     * Retrieves session object.
     *
     * @param request
     * @param sessionName
     * @return
     */
    public static Object getSessionValue(HttpServletRequest request, String sessionName) {
        HttpSession session = request.getSession(false);
        if (session != null)
            return session.getAttribute(sessionName);

        return null;
    }

    /**
     * Removes the required session attribute.
     *
     * @param request
     * @param sessionName
     */
    public static void clearSessionValue(HttpServletRequest request, String sessionName) {
        HttpSession session = request.getSession(false);
        if (session != null)
            session.removeAttribute(sessionName);
    }

    /**
     * Remove all session attributes.
     *
     * @param session
     */
    public static void clearAllSessionAttributes(HttpSession session) {
        Enumeration enumSession = session.getAttributeNames();
        String name;

        for (; enumSession.hasMoreElements();) {
            // Get the name of the attribute
            name = (String) enumSession.nextElement();

            // Get the value of the attribute
            if(!name.equalsIgnoreCase(org.apache.struts.Globals.LOCALE_KEY))
            	session.removeAttribute(name);
        }
    }
    
    /**
     * Retrieves user object from session. If not found, attach the error message to the request object
     *
     * @param request
     * @return
     * @throws Exception
     * 
     */
    public static UserSession getSessionUser(HttpServletRequest request) throws Exception 
    {

        UserSession usrSessionParam = (UserSession) getSessionValue(request,"SESSION_USER");
        if (usrSessionParam == null) {        	
            throw new Exception("User session not found. Please make sure that user is logged in.");
        }
        return usrSessionParam;
    }    
    
       
    /**
     * Validates the date of birth and date joined. <p>
     * The date of birth cannot be greater than date joined.
     * 
     * @param dob
     * @param dateJoined
     * @param errors
     * @return
     */
    public static boolean checkDate (String dob, String dateJoined, 
    		ActionMessages errors) {
    	
    	boolean flag = false;
    	
        //	Date of birth cannot be greater than Date Joined.
        if (!StringUtil.isEmpty(dob) && !StringUtil.isEmpty(dateJoined) &&
                DateUtil.checkFutureDate(dob, dateJoined,"dd/MM/yyyy")) {
        	flag = true;
        }    	
    	return flag;
    }
    
    /**
     * Verifies if the uploaded file is in the correct image format.<p>
     * The acceptable image formats are:<p>
     * - jpeg <p>
     * - jpg <p>
     * - JPEG
     * 
     * @param imageName
     * @return
     */
    public static boolean checkValidImageFormat (String imageName) {
    	boolean flag = false;
    	
    	log.debug("===== Checking image format: " + imageName);
    	
    	if (!StringUtil.isEmpty(imageName)) {
    		
    		//convert image name to lower case for easy string manipulation
    		imageName.toLowerCase();
    		
    		if (imageName.endsWith("jpg") ||
    				imageName.endsWith("jpeg") ||
    				imageName.endsWith("jpe") ||
    				imageName.endsWith("jfif") ||
    				imageName.endsWith("gif") ||
    				imageName.endsWith("tif") ||
    				imageName.endsWith("tiff") ||
    				imageName.endsWith("png") ||
    				imageName.endsWith("bmp")) {
    			log.debug("===== Image is in valid format.");
    			flag = true;
    		}
    	}
    	
    	return flag;
    }
    
    /**
     * Converts a collection of LabelValueBean objects, taking the value into a string with the separator specified
     * 
     * @param collection the collection of LabelValueBean objects 
     * @param separator if null, comma will be used in separator
     * @return
     */
    public static String convertValueCol2String(Collection<LabelValueBean> collection, String separator) {
    	
    	if (collection == null || collection.size() == 0)
    		return "";
    	
    	if (separator == null || separator.length() == 0) 
    		separator = ","; //default
    	
		StringBuffer sb = new StringBuffer();
		for (LabelValueBean lvb : collection) {
			
			if (lvb != null && lvb.getValue() != null) {
				if (sb.length() != 0) 
					sb.append(separator);
				sb.append(lvb.getValue());				
			}
			
		}		
		
		return sb.toString();
   	
    }
    
    /**
     * Converts a collection of LabelValueBean objects, taking the label into a string with the separator specified
     * 
     * @param collection the collection of LabelValueBean objects 
     * @param separator if null, comma will be used in separator
     * @return
     */
    public static String convertLabelCol2String(Collection<LabelValueBean> collection, String separator) {
    	
    	if (collection == null || collection.size() == 0)
    		return "";
    	
    	if (separator == null || separator.length() == 0) 
    		separator = ","; //default
    	
		StringBuffer sb = new StringBuffer();
		for (LabelValueBean lvb : collection) {
			
			if (lvb != null && lvb.getLabel() != null) {
				if (sb.length() != 0) 
					sb.append(separator);
				sb.append(lvb.getLabel());				
			}
			
		}		
		
		return sb.toString();
   	
    }    
}
